package com.yumeng.framework.core.mvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

/**
 * 全局请求处理
 *
 * @author wxd
 * @date 2024/6/7 下午4:38
 */
@Slf4j
public class BaseGlobalRequestBodyAdvice implements RequestBodyAdvice {

    //@Value("${http.body.AESKey}")
    public String AESKey;

    //@Value("${http.body.MD5Key}")
    public String MD5Key;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (log.isDebugEnabled()){
            log.debug("BaseGlobalRequestBodyAdvice supports");
        }
/*        //解密注解（方法）
        boolean methodHasHttpBodyDecrypt = methodParameter.hasMethodAnnotation(HttpBodyDecrypt.class);
        if (methodHasHttpBodyDecrypt) {
            return true;
        }
        //解密注解（类）
        boolean classHasHttpBodyDecrypt = methodParameter.getDeclaringClass().getAnnotation(HttpBodyDecrypt.class) != null;
        if (classHasHttpBodyDecrypt) {
            return true;
        }*/
        return false;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        if (log.isDebugEnabled()){
            log.debug("BaseGlobalRequestBodyAdvice beforeBodyRead");
        }
        return inputMessage;

        /*if (inputMessage.getBody().available()<=0) {
            return inputMessage;
        }
        byte[] requestDataByte=new byte[inputMessage.getBody().available()];
        inputMessage.getBody().read(requestDataByte);
        byte[] requestDataByteNew=null;
        try {
            // 解密
            requestDataByteNew  = this.decryptHandler(requestDataByte);
        } catch (Exception e) {
            throw e;
        }
        // 使用解密后的数据，构造新的读取流
        InputStream rawInputStream = new ByteArrayInputStream(requestDataByteNew);
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                return rawInputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };*/
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (log.isDebugEnabled()){
            log.debug("BaseGlobalRequestBodyAdvice afterBodyRead");
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (log.isDebugEnabled()){
            log.debug("BaseGlobalRequestBodyAdvice handleEmptyBody");
        }
        return body;
    }

    /**
     * AES解密 加MD5签名验证。
     * 来源 网络 待整理
     * @param requestBytes
     * @return
     */
    public byte[] decryptHandler(byte[] requestBytes) throws UnsupportedEncodingException {
/*        if (requestBytes.length <= 0) {
            return new byte[0];
        }
        String requestData = new String(requestBytes, StandardCharsets.UTF_8);
        JSONObject jsonobj = JSON.parseObject(requestData);
        String encrypt= jsonobj.get("encrypt")==null?"":jsonobj.get("encrypt").toString();
        String decrypt = "";
        if (encrypt.length() > 0) {
            //解密参数
            decrypt = AESUtil.AESDecode(encrypt, AESKey);
            if (decrypt == null) {
                //解密失败，返回异常
                throw new BusinessException(ResultCode.PARAM_FUNCTION_IS_ILLEGAL);
            }
        }

        //获取并验证签名。
        String sign = jsonobj.get("sign")==null?"":jsonobj.get("sign").toString();
        String md5Data = MD5Util.MD5(decrypt+MD5Key);
        if (!sign.equals(md5Data)) {
            //验签失败
            throw new BusinessException(ResultCode.PARAM_FUNCTION_IS_ILLEGAL);
        }
        //验证通过，返回解密后的参数
        return decrypt.getBytes(StandardCharsets.UTF_8);*/

        return null;
    }

    /**
     * 解密 来源网络 待整理
     * @return
     */
    private HttpInputMessage decryptHandler2(){
        /*String encoding = "UTF-8";
        //①：获取http请求中原始的body
        String body = IOUtils.toString(inputMessage.getBody(), encoding);
        //②：解密body，EncryptionUtils源码在后面
        String decryptBody = EncryptionUtils.desEncrypt(body);
        //将解密之后的body数据重新封装为HttpInputMessage作为当前方法的返回值
        InputStream inputStream = IOUtils.toInputStream(decryptBody, encoding);
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                return inputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };*/
        return null;
    }

}
